<template>
    <Transition>
        <div class="contain" v-if="flag">
            <div class="card" style="min-width:900px;">
                <div class="header flex">
                    <div class="goHome flex">
                        <p class="title">新增出库单</p>
                    </div>
                    <div class="flex">
                        <!-- <button class="submit" @click="printHandle">打印</button> -->
                        <!-- <button class="submit" @click="addHandle"
                            v-loading.fullscreen.lock="fullscreenLoading">提交</button> -->
                        <!-- <div class="applyBtn" style="margin-right:50px;" @click="addHandle"
                            v-loading.fullscreen.lock="fullscreenLoading">添加一条申领
                        </div> -->
                        <el-icon size="22" style="margin-right: 37px; cursor: pointer;" @click="close">
                            <Close />
                        </el-icon>
                    </div>
                </div>
                <div class="main">
                    <h4 style="margin-bottom: 10px;">基本信息</h4>
                    <div class="main_li">
                        <div class="inputBox">
                            <p class="inputName" style="cursor: pointer;">申领人<span>*</span></p>
                            <el-select v-model="form.requestorId" placeholder="请选择申领人" class="select" clearable
                                filterable @change="changeHandle" allow-create
                                :disabled="applyFlag || printList.length > 0 || submitFlag">
                                <el-option v-for="item in userList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </div>
                        <div class="inputBox">
                            <p class="inputName" style="cursor: pointer;">申领科室<span>*</span></p>
                            <!-- <input type="text" class="myInput" placeholder="请填写申领科室" v-model="form.department"> -->
                            <el-select v-model="form.department" placeholder="请选择申领科室" class="select" clearable
                                filterable allow-create @change="changeDepart"
                                :disabled="printList.length > 0 || submitFlag">
                                <el-option v-for="item in departmentList" :key="item.id" :label="item.name"
                                    :value="item.name" />
                            </el-select>

                        </div>
                        <div class="inputBox">
                            <p class="inputName">备注</p>
                            <input type="text" class="myInput" placeholder="请填写备注" v-model="form.remark"
                                :disabled="submitFlag">
                        </div>
                    </div>


                    <h4 style="margin-bottom: 10px;">库存物资</h4>
                    <div class="main_li">
                        <div class="inputBox">
                            <p class="inputName">申领物资<span>*</span></p>
                            <el-select v-model="form.materialId" placeholder="请选择申领物资" class="select" clearable
                                filterable @change="changeMaterial" :disabled="submitFlag" @clear="clearMaterial">
                                <el-option v-for="item in assetsList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </div>
                        <div class="inputBox">
                            <p class="inputName">批次<span>*</span></p>
                            <el-select v-model="batchNo" placeholder="请选择批次" class="select" clearable filterable
                                @change="changeBatchNo" @clear="clearHandle" :disabled="submitFlag">
                                <el-option v-for="item in batchList" :key="item.id" :label="item.batchNo"
                                    :value="item.id" />
                            </el-select>
                        </div>

                        <div class="inputBox">
                            <p class="inputName">申领数量<span>*</span> <span style="color: #1E9FFF;">(单价：{{ price
                                    }}，可用数量：{{ availableQuantity }})</span>
                            </p>
                            <input type="number" min="0" class="myInput" :placeholder="unit" v-model="form.quantity"
                                @input="inputHandle" :disabled="submitFlag">
                        </div>
                    </div>


                    <div style="display: flex; align-items: center; justify-content: flex-start;margin-top: 10px;">
                        <div class="applyBtn" @click="addHandleCopy" v-if="!submitFlag">加入出库单</div>
                        <div class="applyBtn" @click="printHandleCopy('仅保存')" v-if="!submitFlag"
                            v-loading.fullscreen.lock="fullscreenLoading" style="margin-left: 30px;">仅保存</div>
                        <div class="applyBtn" @click="printHandleCopy('保存并打印')" v-if="!submitFlag"
                            v-loading.fullscreen.lock="fullscreenLoading" style="margin-left: 30px;">保存并打印
                        </div>
                        <div class="applyBtn" v-if="submitFlag" @click="printHandle"
                            v-loading.fullscreen.lock="fullscreenLoading">打印</div>
                        <button class="applyBtn" style="margin-left: 30px;" v-if="submitFlag"
                            @click="toExcel">下载</button>
                    </div>
                </div>



                <div class="printMain" id="printMain" ref="print">
                    <div>
                        <h3 class="printTitle">{{ schoolName }}卫生材料领用单</h3>
                    </div>
                    <div class="flex printPage">
                        <p class="signature">NO.Y{{ printForm.printNumber }}</p>
                        <div class="flex Pagination">
                        </div>
                    </div>
                    <div class="flex centerBox">
                        <p>库房：物资库房</p>
                        <p>领用科室：{{ printForm.department }}</p>
                        <p>领用人：{{ printForm.people }}</p>
                        <p> &emsp;</p>
                    </div>
                    <div class="table_box">
                        <el-table :data="printList" border style="width: 100%;font-size: 14px;" class="custom-table"
                            :header-cell-style="{ 'background': '#F6F6FE', 'color': '#5B686D' }" size="small"
                            :cell-style="{ 'color': '#5B686D' }">
                            <el-table-column type="index" label="序号" width="45" />
                            <el-table-column prop="name" label="材料信息" min-width="200" />
                            <el-table-column prop="categoriesName" label="材料分类" />
                            <el-table-column prop="specification" label="规格" />
                            <el-table-column prop="unit" label="单位" />
                            <el-table-column prop="quantity" label="数量" />
                            <el-table-column prop="price" label="售价">
                                <template #default="scope">
                                    <span>{{ parseFloat(scope.row.price).toFixed(5) }}</span>
                                </template>
                            </el-table-column>

                            <el-table-column prop="finalSellingPrice" label="售价金额">
                                <template #default="scope">
                                    <span>{{ (parseFloat(scope.row.quantity) * parseFloat(scope.row.price)).toFixed(5)
                                        }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="100px" v-if="!submitFlag">
                                <template #default="scope">
                                    <el-button type="danger" style="padding: 0 10px;"
                                        @click="deleteHandle(scope.row, scope.$index)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="flex footer">
                            <p class="p1">&emsp;摘要</p>
                            <p class="p2">&emsp;填制人：{{ user.name }}</p>
                            <p class="p2">&emsp;填制日期：{{ nowDate }}</p>
                            <p class="p2">&emsp;领料人签字：</p>
                        </div>
                    </div>


                </div>

            </div>
            <!-- <div style="width: 1px;height: 100px;"></div> -->
        </div>
    </Transition>
</template>

<script>
import { httpService } from "@/utils/httpService";
import Icon from '@/components/Icon.vue';
import { ArrowLeft, Close } from "@element-plus/icons-vue";
import { ElMessage, ElForm, ElLoading } from "element-plus";
import { getCurrentInstance } from "vue";
import { formatTime } from "@/utils/dateFormat";

import * as XLSX from "xlsx";
import XLSXS from "xlsx-style"
import { saveAs } from "file-saver";

export default {
    name: "leftMenu",
    components: { Icon, ArrowLeft, ElMessage, ElForm, ElLoading, Close },
    data() {
        return {

            flag: false,
            form: {
                requestorId: "",
                requestor: "",
                materialId: "",
                quantity: "",
                remark: "",
                department: "",
                batchNo: "",
                categoriesName: "",
                printName: "",
                printSpec: "",
                printUnit: "",
                printPrice: "",
                printMoney: "",
            },
            printForm: {
                people: "",
                department: "",
                printNumber: "",
            },
            formRules: {
                requestor: "请选择申领人",
                materialId: "请选择申领物资",
                quantity: "请填写申领数量",
                remark: "请填写备注",
                department: "请填写申领部门",
            },
            batchNo: "",
            price: "",
            availableQuantity: "",
            unit: "请填写申领数量",
            fullscreenLoading: false,
            assetsList: [],
            userList: [],
            departmentList: [],
            batchList: [],
            applyFlag: false,

            printList: [],
            printList1: [],
            printTotal: 0,
            printAllPage: 0,
            printPage: 1,
            schoolName: "",
            user: {},
            nowDate: "",

            submitFlag: false,
        };
    },
    computed: {

    },

    mounted() {
        // this.getDepartmentList()
        // this.getAssetsList()
        // this.getUserList()
        this.nowDate = formatTime(new Date())
        this.user = JSON.parse(sessionStorage.getItem("user"))
        const instance = getCurrentInstance()
        this.schoolName = instance.appContext.config.globalProperties.$schoolName

    },
    methods: {
        addHandleCopy() {
            // console.log(this.form);
            let obj = {
                name: "",
                categoriesName: "",
                specification: "",
                unit: "",
                quantity: "",
                price: "",
                finalSellingPrice: "",
            }
            let obj1 = {
                requestor: this.form.requestor,
                materialId: this.form.materialId,
                quantity: this.form.quantity,
                department: this.form.department,
                // remark: this.form.remark,
                batchNo: this.form.batchNo,
                price: this.price,
            }
            obj.name = this.form.printName
            obj.categoriesName = this.form.categoriesName
            obj.specification = this.form.printSpec
            obj.unit = this.form.printUnit
            obj.quantity = this.form.quantity
            obj.price = this.form.printPrice
            obj.finalSellingPrice = this.form.printMoney

            if (!obj1.requestor) {
                ElMessage.error("请选择申领人")
            } else if (!obj1.department) {
                ElMessage.error("请填写申领科室")
            } else if (!obj1.materialId) {
                ElMessage.error("请选择申领物资")
            } else if (!this.batchNo) {
                ElMessage.error("请选择批次")
            } else if (!obj1.quantity) {
                ElMessage.error("请填写申领数量")
            } else {
                this.printList.push(obj)
                this.printList1.push(obj1)
                this.clear()

            }
        },
        printHandleCopy(str) {
            if (this.printList1.length <= 0) {
                ElMessage.error("出库单为空，请添加物资后点击保存并打印");
                return
            }

            this.fullscreenLoading = true

            let params = new FormData()
            params.append("json", JSON.stringify(this.printList1))
            params.append("department", this.form.department)
            params.append("remark", this.form.remark)
            params.append("requestor", this.form.requestor)
            params.append("status", 1)
            let userInfo = sessionStorage.getItem('user')
            userInfo = JSON.parse(userInfo);
            let campus = 2;
            if(userInfo&&userInfo.teacherNumber=='240085'){
                campus = 2;
            }else{
                campus = 1;
            }
            params.append("campus", campus)
            httpService("/javaApi/stockOutReceipt/add", params, "post").then((data) => {
                this.fullscreenLoading = false
                if (data.code == 200) {
                    this.submitFlag = true
                    ElMessage.success("申领成功");
                    if (str && str == '保存并打印') {
                        setTimeout(() => {
                            this.printHandle()
                        }, 100)
                    }
                } else {
                    ElMessage.error(data.message ? data.message : data.object ? data.object : "申领失败");
                }
            });

        },
        deleteHandle(data, index) {
            this.printList.splice(index, 1);
            this.printList1.splice(index, 1);
        },
        clearHandle() {
            // console.log('清空了');
            // this.price = ""
            // this.availableQuantity = ""
        },


        printHandle() {
            const itemsPerPage = 10; // 每页最多打印的条目数
            const totalPages = Math.ceil(this.printList.length / itemsPerPage); // 总页数
            // const baseNumber = this.printForm.printNumber; // 原始编号，如 "Y000001"

            // // 提取编号中的非数字和数字部分
            // const prefix = baseNumber.match(/^\D+/)[0]; // 提取非数字部分 "Y"
            // const startNumber = parseInt(baseNumber.match(/\d+$/)[0], 10); // 提取数字部分 "000001"

            // 将数据分成每页的组
            const paginatedList = Array.from({ length: totalPages }, (_, i) =>
                this.printList.slice(i * itemsPerPage, (i + 1) * itemsPerPage)
            );

            let totalSum = 0; // 初始化合计为 0

            // 生成 HTML 内容
            const printContent = paginatedList.map((pageItems, pageIndex) => {
                // 根据页码生成新的编号
                // const currentNumber = prefix + String(startNumber + pageIndex).padStart(6, '0'); // 保证编号长度为6位

                // 计算本页小计
                const pageSum = pageItems.reduce((sum, item) => {
                    const itemTotal = (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
                    return sum + itemTotal;
                }, 0);

                totalSum += pageSum; // 累加到总计

                return `
            <div class="table-container">
                <p class="pTitle">${this.schoolName}卫生材料领用单</p>
                <div class="table-header">
                    <div>NO.Y${this.printForm.printNumber}</div> <!-- 页码递增 -->
                    <div>第 ${pageIndex + 1} 页/共 ${totalPages} 页</div>
                </div>
                <div class="table-info">
                    <span>库房: 物资库房</span>
                    <span>领用科室: ${this.printForm.department}</span>
                    <span>领用人: ${this.printForm.people}</span>
                    <span> </span>
                </div>
                <table>
                    <thead>
                        <tr>
                            <td>材料信息</td>
                            <td>材料分类</td>
                            <td>规格</td>
                            <td>单位</td>
                            <td>数量</td>
                            <td>售价</td>
                            <td>售价金额</td>
                        </tr>
                    </thead>
                    <tbody>
                        ${pageItems.map(item => {
                    const itemTotal = (parseFloat(item.quantity) || 0) * (parseFloat(item.price) || 0);
                    return `
                                <tr>
                                    <td>${item.name}</td>
                                    <td>${item.categoriesName}</td>
                                    <td>${item.specification}</td>
                                    <td>${item.unit}</td>
                                    <td>${item.quantity}</td>
                                    <td>${parseFloat(item.price).toFixed(5)}</td>
                                    <td>${itemTotal.toFixed(5)}</td>  
                                </tr>
                            `;
                }).join('')}
                        <tr>
                            <td>本页小计</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td>${pageSum.toFixed(5)}</td>
                        </tr>
                        <tr>
                            <td>合&emsp;计</td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td></td>
                            <td>${totalSum.toFixed(5)}</td>
                        </tr> 
                    </tbody>
                </table>
                <div class="table-footer">
                    <div>摘要</div>
                    <div>填制人: ${this.user.name}</div>
                    <div>填制日期: ${this.nowDate}</div>
                    <div>领料人签字: &emsp; &emsp; &emsp; &emsp; &emsp; &emsp;</div>
                </div>
            </div>
            <div style="page-break-after: always;"></div> <!-- 确保分页 -->
        `;
            }).join('');

            // 创建打印窗口
            const WinPrint = window.open('', '', 'width=800,height=600');
            WinPrint.document.write(`
        <html>
        <head>
            <title>打印</title>
            <style>
                @media print { 
                    @page {
                        margin: 30px 20mm;
                    }
                    body {
                        margin: 0;
                        font-family: Arial, sans-serif;
                    }
                    .table-container {
                        width: 100%;
                        text-align: center;
                        page-break-before: always; /* 强制每个新内容开始时分页 */
                    }
                    .table-container:last-child {
                        page-break-after: auto; /* 最后一页不分页 */
                    }
                    .table-header,
                    .table-info,
                    .table-footer {
                        display: flex;
                        justify-content: space-between; 
                    }
                    .pTitle {
                        font-size: 20px;
                        font-weight: 400;
                        text-align: center;
                    }
                    table {
                        width: 100%;
                        border: 1px solid #000;
                        border-collapse: collapse;
                    }
                    th, td {
                        border: 1px solid #000; 
                        text-align: center;
                    }
                    tr:nth-child(even) {
                        background-color: #f2f2f2; /* 隔行变色 */
                    }
                }
            </style>
        </head>
        <body>
            ${printContent}
        </body>
        </html>
    `);
            WinPrint.document.close();
            WinPrint.print();
            WinPrint.close();
        },


        changeHandle(value) {
            const user = this.userList.filter(item => item.id == value)
            if (user.length > 0) {
                this.form.requestor = user[0].name
                this.printForm.people = user[0].name
            } else {
                this.form.requestor = value
            }
        },
        changeDepart(value) {
            this.printForm.department = value
        },
        changeMaterial(value) {
            const arr = this.assetsList.filter(item => item.id == value)
            if (arr.length > 0) {
                this.unit = `请填写申领数量（单位：${arr[0].unit})`
                this.batchNo = ''
                this.price = ''
                this.availableQuantity = ""
                this.form.categoriesName = arr[0].categoriesName
                this.form.printName = arr[0].name
                this.form.printSpec = arr[0].specification
                this.form.printUnit = arr[0].unit
                this.form.printMoney = arr[0].finalSellingPrice
                this.getsStockInListAll(arr[0].id)
            }
        },
        clearMaterial() {
            this.unit = `请填写申领数量`
            this.batchNo = ''
            this.form.quantity = ""
            this.price = ''
            this.availableQuantity = ""
            this.form.categoriesName = ""
            this.form.printName = ""
            this.form.printSpec = ""
            this.form.printUnit = ""
            this.form.printMoney = ""
        },
        changeBatchNo(value) {
            const arr = this.batchList.filter(item => item.id == value)
            if (arr.length > 0) {
                this.price = arr[0].price
                this.form.printPrice = arr[0].price
                this.availableQuantity = arr[0].availableQuantity
                this.form.batchNo = arr[0].batchNo
            }
        },
        inputHandle() {
            if (Number(this.form.quantity) > Number(this.availableQuantity)) {
                this.form.quantity = ""
                ElMessage.error("申领数量不能大于可用数量，请重新填写！");
            }
        },
        getsStockInListAll(id) {
            httpService(
                "/javaApi/stockIn/listAll", { materialId: id }, "get"
            ).then((data) => {
                this.batchList = data
            });
        },

        addHandle() {
            if (!this.form.requestor) {
                ElMessage.error("请选择申领人")
            } else if (!this.form.materialId) {
                ElMessage.error("请选择申领物资")
            } else if (!this.batchNo) {
                ElMessage.error("请选择批次")
            } else if (!this.form.department) {
                ElMessage.error("请填写申领部门")
            } else if (!this.form.quantity) {
                ElMessage.error("请填写申领数量")
            } else {

                this.fullscreenLoading = true
                let params = new FormData()
                params.append("requestor", this.form.requestor)
                params.append("materialId", this.form.materialId)
                params.append("quantity", this.form.quantity)
                params.append("department", this.form.department)
                params.append("remark", this.form.remark ? this.form.remark : "")
                params.append("batchNo", this.form.batchNo ? this.form.batchNo : "")
                params.append("price", this.price ? this.price : "")
                params.append("status", 1)

                httpService("/javaApi/stockOut/add ", params, "post").then((data) => {
                    this.fullscreenLoading = false
                    if (data.code == 200) {
                        ElMessage.success("出库成功");

                        this.clear();
                        // this.$parent.getList();
                    } else {
                        // ElMessage.error("申领失败");
                        ElMessage.error(data.message ? data.message : data.object ? data.object : "申领失败");
                    }
                });
            }
        },
        getDepartmentList() {
            httpService(
                "/javaApi/baseDepartment/list/1/1000",
                {
                    type: 1,
                    noCampus: 1,
                },
                "get"
            ).then((data) => {
                this.departmentList = data.list;
            });
        },
        getAssetsList() {
             //从缓存中获取用户的信息，判断,临时的写法，后续需要修改
             let userInfo  = sessionStorage.getItem('user')
            userInfo = JSON.parse(userInfo);
            let campus = 2;
            if(userInfo&&userInfo.teacherNumber=='240085'){
                campus = 2;
            }else{
                campus = 1;
            }
            httpService("/javaApi/materials/list/1/10000", {campus:campus}, "get").then((data) => {
                if (data) {
                    data.list.map(item => item.name = `${item.name} (单位：${item.unit}，规格：${item.specification} )`)
                    this.assetsList = data.list
                }
            });
        },
        getUserList() {
          
            httpService("/javaApi/baseTeacher/list/1/10000", { noCampus: 1, }, "get").then((data) => {
                if (data) {
                    this.userList = data.list
                }
            });
        },
        getIdList() {
            let userInfo  = sessionStorage.getItem('user')
            userInfo = JSON.parse(userInfo);
            let campus = 2;
            if(userInfo&&userInfo.teacherNumber=='240085'){
                campus = 2;
            }else{
                campus = 1;
            }
            httpService("/javaApi/stockOutReceipt/list/1/1", {campus:campus}, "get").then((data) => {
                if (data && data.list.length > 0) {
                    let num = parseFloat(data.list[0].receiptCode) + 1
                    this.printForm.printNumber = num
                    console.log(num);
                }
            });
        },
        close() {
            this.flag = false
            this.form.requestorId = ""
            this.form.requestor = ""
            this.form.department = ""
            this.form.remark = ""
            this.printList = []
            this.printList1 = []
            this.printForm.printNumber = ''
            // this.$parent.getList();
            this.submitFlag = false
        },
        clear() {
            this.form.id = ""
            this.form.materialId = ""
            this.form.quantity = ""
            this.form.categoriesName = ""
            this.unit = "请填写申领数量"
            this.unit = "请填写申领数量"
            this.batchNo = ""
            this.price = ""
            this.availableQuantity = ""
            this.batchList = ""
        },
        queryById(id) {
            httpService("/javaApi/baseTeacher/queryById", { id: id }, "get").then((data) => {
                if (data) {
                    this.form = data
                }
            });
        },


        toExcel() {
            const data = this.printList; // 数据列表
            const rowsPerPage = 10; // 每页显示的行数
            const sheetData = [];
            const merges = []; // 合并单元格信息
            let pageCount = 1;

            const title = `${this.schoolName}卫生材料领用单`
            const number = `NO.Y${this.printForm.printNumber}`
            const page = `第一页/共三页`
            const department = `领用科室: ${this.printForm.department}`
            const personal = `领用人: ${this.printForm.people}`
            const teacher = `填制人: ${this.user.name}`
            const time = `填制日期: ${this.nowDate}`






            data.forEach((item, index) => {
                // 每页开始时添加表头
                if (index % rowsPerPage === 0) {
                    const startRow = sheetData.length;
                    // 表头部分
                    sheetData.push([title, "", "", "", "", "", ""]);
                    sheetData.push([
                        number,
                        "",
                        "",
                        `第${pageCount}页/共${Math.ceil(data.length / rowsPerPage)}页`,
                        "",
                        "",
                        ""
                    ]);
                    sheetData.push([
                        "库房：物资库房",
                        "",
                        department,
                        "",
                        personal,
                        "",
                        ""
                    ]);
                    sheetData.push([
                        "材料信息",
                        "材料分类",
                        "规格",
                        "单位",
                        "数量",
                        "售价",
                        "售价金额"
                    ]);
                    // 添加表头的合并范围
                    merges.push(
                        { s: { r: startRow, c: 0 }, e: { r: startRow, c: 6 } }, // 标题合并
                        { s: { r: startRow + 1, c: 0 }, e: { r: startRow + 1, c: 2 } },
                        { s: { r: startRow + 1, c: 3 }, e: { r: startRow + 1, c: 6 } },
                        { s: { r: startRow + 2, c: 0 }, e: { r: startRow + 2, c: 1 } },
                        { s: { r: startRow + 2, c: 2 }, e: { r: startRow + 2, c: 3 } },
                        { s: { r: startRow + 2, c: 4 }, e: { r: startRow + 2, c: 5 } }
                    );
                    pageCount++;
                }
                // 添加数据行
                sheetData.push([
                    item.name.split("(")[0],
                    item.categoriesName,
                    item.specification,
                    item.unit,
                    item.quantity,
                    item.price,
                    item.quantity * item.price
                ]);
                // 添加表尾
                if ((index + 1) % rowsPerPage === 0 || index === data.length - 1) {
                    const footerStartRow = sheetData.length;
                    sheetData.push([
                        "摘要",
                        teacher,
                        "",
                        time,
                        "",
                        "领料人签字：",
                        "",
                    ]);
                    merges.push(
                        { s: { r: footerStartRow, c: 0 }, e: { r: footerStartRow, c: 0 } },
                        { s: { r: footerStartRow, c: 1 }, e: { r: footerStartRow, c: 2 } },
                        { s: { r: footerStartRow, c: 3 }, e: { r: footerStartRow, c: 4 } },
                        { s: { r: footerStartRow, c: 5 }, e: { r: footerStartRow, c: 6 } },
                    );
                    // 添加间隔行
                    sheetData.push([], []);
                }
            });
            // 生成工作表
            let ws = XLSX.utils.aoa_to_sheet(sheetData);
            // 添加合并单元格信息
            ws["!merges"] = merges;
            // 设置边框和样式
            ws = this.setExlStyle(ws);
            // 导出 Excel
            let wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "分组表");
            const excelData = XLSX.write(wb, { bookType: "xlsx", type: "array" });
            var table = XLSXS.write(wb, {
                type: "buffer"
            });
            try {
                saveAs(
                    new Blob([table], { type: "application/octet-stream" }),
                    `${title}.xlsx`
                );
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, table);
            }
            return table;
        },

        setExlStyle(data) {
            const borderAll = { // 单元格外侧框线
                top: { style: "thin" },
                bottom: { style: "thin" },
                left: { style: "thin" },
                right: { style: "thin" }
            };
            // 获取工作表的范围
            const range = XLSX.utils.decode_range(data["!ref"]);
            for (let R = range.s.r; R <= range.e.r; ++R) {
                for (let C = range.s.c; C <= range.e.c; ++C) {
                    const cellAddress = XLSX.utils.encode_cell({ r: R, c: C });
                    if (!data[cellAddress]) {
                        data[cellAddress] = { v: "" }; // 如果单元格没有内容，设置为空字符串
                    } else {
                        data[cellAddress].s = {
                            border: borderAll, // 添加边框
                            alignment: {
                                horizontal: "center", // 水平居中对齐
                                vertical: "center"    // 垂直居中对齐
                            }
                        };
                    }
                }
            }
            // 设置列宽
            data["!cols"] = [
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 }
            ];
            return data;
        },




    },
}
</script>

<style scoped>
* {
    margin: 0;
    padding: 0;
}

.flex {
    display: flex;
    align-items: center;
}

.contain {
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.35);
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 99;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    overflow-y: auto;
}

.card {
    width: 60%;
    height: calc(100vh - 100px);
    background-color: #fff;
    border-radius: 13px;
    margin-top: 50px;
    margin-bottom: 50px;
}

.table_box {
    height: calc(100vh - 620px);
    overflow: auto;
}

.header {
    justify-content: space-between;
    height: 65px;
    border-bottom: 1px solid #D6DBE2;
}

.header .title {
    color: #000000;
    font-size: 18px;
    font-weight: bold;
    margin-left: 32px;
}

.submit {
    width: 77px;
    height: 38px;
    background-color: #6F72FF;
    border-radius: 10px;
    border: none;
    margin-right: 32px;
    color: #fff;
    font-size: 15px;
}

.main {
    padding: 0px 60px 0 60px;
    margin: 10px auto 0;
    overflow-y: auto;
}

.main_li {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.inputBox {
    width: calc((100% - 90px) / 3);
    /* width: calc((100% - 100px) / 2); */
    margin-bottom: 15px;
}

.inputName {
    color: #5B686D;
    font-size: 15px;
    margin-bottom: 5px;
}

.inputName span {
    color: #FF0000;
    font-size: 15px;
    margin-bottom: 5px;
}

.myInput {
    width: calc(100% - 19px);
    height: 42px;
    border-radius: 10px;
    border: 1px solid #D6DBE2;
    outline: none;
    font-size: 15px;
    color: #000;
    padding-left: 19px;
}

.myInput::placeholder {
    color: #A9B6BB;
}

.myText {
    width: calc(100% - 36px);
    height: 150px;
    border-radius: 10px;
    border: 1px solid #D6DBE2;
    resize: none;
    outline: none;
    padding: 18px;
    font-size: 15px;
    color: #000;
}

.myText::placeholder {
    color: #A9B6BB;
}


input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
}

/* 对于Firefox */
input[type="number"] {
    -moz-appearance: textfield;
}



.select ::v-deep .el-tooltip__trigger {
    width: 100%;
    height: 44px;
    border-radius: 10px;
}

.el-select-dropdown__item {
    padding-left: 15px;
}

::v-deep .el-select {
    --el-color-primary: #D6DBE2;
}



.v-enter-active,
.v-leave-active {
    transition: opacity 0.5s ease;
}

.v-enter-from,
.v-leave-to {
    opacity: 0;
}
</style>

<style>
.printMain {
    margin: 10px 60px 0;
}

.printTitle {
    text-align: center;
    margin-bottom: 10px;
    color: #2B2B2B;
    font-size: 17px;
}

.printPage {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.signature {
    color: #2B2B2B;
    font-size: 17px
}

.Pagination {
    color: #2B2B2B;
    font-size: 17px;
    display: flex;
    align-items: center;
}

.nextBtn {
    color: #6F72FF;
    margin-left: 30px;
}

.centerBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
}

.footer {
    color: #959EA1;
    font-size: 15px;
    margin-top: 10px;
    display: flex;
    align-items: center;
}

.p1 {
    width: calc(100% / 7);
}

.p2 {
    width: calc((100% / 7) * 2)
}


.applyBtn {
    width: 100px;
    line-height: 35px;
    border-radius: 10px;
    font-size: 15px;
    background-color: #6F72FF;
    color: #fff;
    text-align: center;
    cursor: pointer;
    border: none;
    outline: none;
}
</style>